$(function () {
    //下拉框
    let list = $(".ss_list")
    let list1 = $(".ss_list_bg")
    list.hover(function () {
        list1.slideDown()
    }, function () {
        list1.slideUp()
    })


    function init() {
        //价格高低排序
        let list = $(".cate_list>li")
        let arr = []
        list.each(function (index, item) {
            let src = $(item).find(".img img").attr("src")
            let price = parseFloat($(item).find(".price span").text().substring(1))
            let name = $(item).find("a").text()
            let obj = {
                id: index + 1,
                //属性名和属性值一样可以写一个
                src,
                price,
                name
            }
            arr.push(obj)

        })
        console.log(JSON.stringify(arr));
    }
    init()

    function sort(arr, option) {
        //深度拷贝对象
        let a = JSON.parse(JSON.stringify(arr))
        let n = a.length
        //冒泡排序
        for (let i = 0; i < n - 1; i++) {
            for (let j = 0; j < n - i - 1; j++) {
                if (option === 'up') {
                    if (a[j].price > a[j + 1].price) {
                        let t = a[j]
                        a[j] = a[j + 1]
                        a[j + 1] = t
                    }
                }
                if (option === 'down') {
                    if (a[j].price < a[j + 1].price) {
                        let t = a[j]
                        a[j] = a[j + 1]
                        a[j + 1] = t
                    }
                }
            }
        }
        return a
    }

    //获得商品列表
    function getList(option) {
        $.ajax({
            url: "./js/goods.json",
            success(res) {
                console.log(res);
                let a = sort(res, option)
                //根据option对数组进行排序
                appendEl(a)
            },
            error(e) {
                console.log(e);
            }
        })
    }

    /**
     * 渲染数据
     * @param arr
     */
    function appendEl(arr) {
        console.log(arr)
        let list = $(".cate_list")
        list.empty()
        arr.forEach(function (item, index) {
            let li = `
        <li>
              <div class="img"><a href="#"><img src="${item.src}" width="210" height="185"/></a></div>
              <div class="price">
                <span>￥${item.price}</span>
              </div>
              <div class="name"><a href="#">${item.name}</a></div>
              <div class="carbg">
                <a href="#" class="ss">收藏</a>
                <a href="#" class="j_car">加入购物车</a>
              </div>
            </li>
      `
            list.append(li)
        })
    }

    $(function () {
        getList()
        $('.i_down').click(function () {
            getList("down")
        })
        $('.i_up').click(function () {
            getList("up")
        })
    })

    $(function () {
        // 显示购物车 
        function showCart() {
            let length = $(".shop ul").find('li').length
            console.log(length);
            if (length === 0) {
                $(".shop").hide()
                $('.noshop').show()
            } else {
                $(".shop").show()
                $('.noshop').hide()
            }
        }
        $(".car_t").click(function () {
            $(".last").toggle()
            showCart()
        })

        //  鼠标移出 隐藏购物车
        $(".last").mouseleave(function () {
            // $(this).hide()
        })

        // 点击+改变商品数量 和小计
        $(".shop ul").on('click', '.J_btnAddCount', function () {
            let val = parseInt($(this).siblings('.J_inputCount').val())
            $(this).siblings('.J_inputCount').val(++val)
            val = parseInt($(this).siblings('.J_inputCount').val())
            let price = parseFloat($(this).parent().next().text().substring(1)).toFixed(2)
            if (val <= 1) {
                return
            }
            price = (price / (val - 1)).toFixed(2)
            let sum = val * price
            $(this).parent().next().text('￥' + sum)
            getTotal()
        })


        // 点击-改变商品数量 和小计
        $(".shop ul").on('click', '.J_btnDelCount', function () {
            let val = parseInt($(this).siblings('.J_inputCount').val())
            if (val <= 1) {
                $(this).siblings('.J_inputCount').val(1)
                return
            }
            $(this).siblings('.J_inputCount').val(--val)
            val = parseInt($(this).siblings('.J_inputCount').val())
            if (val <= 0) {
                return
            }
            let price = parseFloat($(this).parent().next().text().substring(1)).toFixed(2)
            price = (price / (val + 1)).toFixed(2)
            let sum = val * price
            $(this).parent().next().text('￥' + sum)
            getTotal()
        })


        // 计算商品总价
        function getTotal() {
            let total = 0
            $(".J_smallTotalPrice").each(function () {
                let sum = parseFloat($(this).text().substring(1))
                total += sum
            })
            total = total.toFixed(2)
            $(".J_totalPrice").text('￥' + total)
            return total
        }
        getTotal()

        // 点击×  删除对应的li
        $(".shop ul").on('click', '.close', function () {
            $(this).parents('li').remove()
            showCart()
            getTotal()
            getNum()
        })

        // 结算按钮
        function getNum() {
            let num = $(".shop li").length
            $(".buy .J_totalCount").text('(' + num + ')')
        }

        // 通过输入框改变商品数量
        $(".shop ul").on('keyup', '.J_inputCount', function () {
            let val = parseInt($(".J_inputCount").val())
            if (isNaN(val) || val <= 1) {
                $(".J_inputCount").val(1)
                return
            }
            $(".J_inputCount").val(val)
        })

        // 获取加购物车的商品信息
        function getGood() {
            let obj = {};
            let count = 0
            $(".cate_list").on('click', '.j_car', function () {
                alert('添加成功');
                let name = $(this).parent().siblings('.name').first().text()
                let price = $(this).parent().siblings('.price').first().text().trim().substring(1)
                let src = $(this).parent().siblings('.img').find('img').attr('src')
                count++
                obj = { id: count, name, price, src }
                addToCart(obj)
                getTotal()
                getNum()
                showCart()
            });
            return obj
        }
        getGood()

        // 添加至购物车
        function addToCart(obj) {
            let li = ` 
                <li>
                      <h4>珠韵首饰旗舰店 <span class="J_count">共1件商品</span></h4>
                      <div class="clear">
                        <div class="shopImg">
                          <img src="${obj.src}" alt="" />
                        </div>
                        <div class="shopText">
                          <div class="clear">
                            <h5>
                             ${obj.name}
                            </h5>
                            <a href=" javascript:;void(0)" class="close J_btnDelete"
                              >X</a
                            >
                          </div>
                          <p>淡水白色近圆珍珠</p>
                          <div class="clear">
                            <div class="plush">
                              <span class="J_btnDelCount">-</span>
                              <input class="J_inputCount" type="text" value="1" />
                              <span class="J_btnAddCount">+</span>
                            </div>
                            <strong class="J_smallTotalPrice">￥${obj.price} </strong>
                          </div>
                        </div>
                      </div>
                      <p>全场包邮</p>
                    </li>
               `
            $(".shop ul").append(li)
        }
    })


})
